package com.example.jucdemo.synchdemo;

/**
 * @Author: Dijah
 * @Date: 2023/3/17 15:49
 * @Desc:
 * 场景： 两个对象访问同一个对象中的同步方法，且同步方法中调用非同步方法
 */
public class demo5 implements Runnable{

    static demo5 instance1 = new demo5();
    static demo5 instance2 = new demo5();

    @Override
    public void run() {
        if (Thread.currentThread().getName().equals("Thread-0")){
            method1();
        }else {
            method0();
        }

    }

    //同步方法
    private synchronized void method0() {
        System.out.println("线程名" + Thread.currentThread().getName()+"同步方法,开始运行");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("线程" + Thread.currentThread().getName() + "同步方法,运行结束。开始调用普通方法");
        method1();
    }

    private void method1() {
        System.out.println("线程名" + Thread.currentThread().getName()+"同步方法,开始运行");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("线程" + Thread.currentThread().getName() + "同步方法,运行结束。开始调用普通方法");
    }

    public static void main(String[] args) {
        Thread thread1 = new Thread(instance1);
        Thread thread2 = new Thread(instance1);
        Thread thread3 = new Thread(instance1);
        thread1.start();
        thread2.start();
        thread3.start();
        while (thread1.isAlive() || thread2.isAlive() || thread3.isAlive()){
        }
        System.out.println("测试结束");
    }
}
